package org.jeecg.common.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanToMapUtils {
	
	private BeanToMapUtils() {
	    super();
	}
	
	private static final Logger logger = LoggerFactory.getLogger(BeanToMapUtils.class);


	public static Map<String, Object> transBean2Map(Object obj) {
		if(obj == null){
			return null;
		}
		Map<String, Object> map = new HashMap<>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				if (!"class".equals(key)) {
					Method getter = property.getReadMethod();
					Object value = getter.invoke(obj);
					if(value != null && StringUtils.isNotBlank(value.toString()))
					{
						map.put(key, value);
					}
					
				}
			}
		} catch (Exception e) {
			logger.error("transBean2Map Error ：{}" , e.getMessage());
		}
		return map;
	}
}
